<?php

namespace app\uniapp\service;

use app\common\exception\MiException;
use app\common\service\CommonSiteConfigService;
use app\model\site\DiyPage;
use app\model\site\Site;
use app\model\site\SiteConfig;
use app\model\site\User;
use app\model\store\GoodsCart;
use app\model\store\StoreManager;
use thans\jwt\exception\TokenBlacklistGracePeriodException;
use thans\jwt\facade\JWTAuth;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;

class UniAuthService
{
    protected string $tokenCachePre = 'uni_login_token_';

    private static ?self $_instance = null;

    public static function instance(): static
    {
        if (!self::$_instance){
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    /**
     * @throws MiException
     */
    public function getSiteId(){
        $uniPlatform = getUniPlatform();
        $appid = getAppid();
        static $siteId = 0;
        if ($uniPlatform == 'web'){ //web端访问
            // 根据域名匹配站点数据
            $domain = request()->domain();
            $siteId = SiteConfig::where('key', CommonSiteConfigService::WEB_SET)
                ->where('value', 'regexp', 's:6:"domain";s:[0-9]{1,}:"'.$domain.'";*')
                ->value("site_id", 0);
        }else if ($uniPlatform == 'mp-weixin'){ // 微信小程序
            // 根据appid匹配站点数据
            $siteId = SiteConfig::where('key', CommonSiteConfigService::WX_MP)
                ->where('value', 'regexp', 's:5:"appid";s:[0-9]{1,}:"'.$appid.'";*')
                ->value("site_id", 0);
        }
        return $siteId;
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws MiException
     */
    public function getSite(){
        $id = $this->getSiteId();
        $info = Site::find($id);
        if(!$info){
            throw new MiException("获取站点信息失败");
        }
        $payConfig = CommonSiteConfigService::instance()->getConfigValue($id, CommonSiteConfigService::PAY_SET);
        $distConfig = CommonSiteConfigService::instance()->getConfigValue($id, CommonSiteConfigService::DIST);
        $pointsConfig = CommonSiteConfigService::instance()->getConfigValue($id, CommonSiteConfigService::POINTS);
        $storeConfig = CommonSiteConfigService::instance()->getConfigValue($id, CommonSiteConfigService::STORE);
        // 是否开启微信支付
        $info->isOnWxPay = $payConfig['wx']['is_on'];
        // 是否开启余额支付
        $info->isOnBalancePay = $payConfig['balance']['is_on'];
        // 是否开启积分功能
        $info->isOnPoints = $pointsConfig['is_on'];
        // 是否开启积分抵扣
        $info->isOnPointsDec = $pointsConfig['is_on'] && $pointsConfig['is_on_dec'];
        // 是否开启分销
        $info->isOnDist = $distConfig['is_on'];
        // 是否开启优惠券
        $info->isOnCoupon = $storeConfig['is_on_coupon'];
        // 是否开启签到
        $info->isOnSign = $storeConfig['is_on_sign'];
        // 申请店长样品基金
        $info->storeManagerPrice = $distConfig['store_manager_price'];
        // 是否开启店长功能
        $info->isOnStoreManager = $distConfig['is_on_store_manager'];

        return $info;
    }


    public function getLoginId(): int
    {
        try {
            $payload = JWTAuth::auth(); //可验证token, 并获取token中的payload部分
            $id = $payload['id']; //可以继而获取payload里自定义的字段，比如uid

        }catch (TokenBlacklistGracePeriodException $e) { // 捕获黑名单宽限期
            // 捕获到黑名单宽限期，说明token超时，单刷新token没有超时，中间件中会刷新token
            $payload = JWTAuth::auth(false); //可验证token, 并获取token中的payload部分
            $id = $payload['id']; //可以继而获取payload里自定义的字段，比如uid
        }catch (\Exception $e){
            $id = 0;
        }

        return $id;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function getLoginInfo(){
        $id = $this->getLoginId();
        if (!$id) return null;
        $user = User::with(['storeManager'])->where('status',1)->find($id);
        if ($user){
            $user->cartNum = GoodsCart::where('user_id', $id)->sum("num");
            $user->storeManager = StoreManager::where('user_id', $user->id)->where('audit_status', 1)->where('status', 1)->find();
        }
        return $user;
    }

//    public function logout(){
//        Cache::delete($this->tokenCachePre.$this->getToken());
//    }

    /**
     * 首页信息
     * @return array|string|null
     * @throws MiException
     */
    public function getIndex(): array|string|null
    {
        $content = DiyPage::where('site_id', $this->getSiteId())
            ->where('page_type', 'index')
            ->where('is_default', 1)
            ->limit(1)
            ->value('content');
        return miUnserialize($content);
    }

    /**
     * 底部导航信息
     * @param int $siteId
     * @return array|string|null
     * @throws MiException
     */
    public function getTabBar(): array|string|null
    {
        $content = $this->getIndex();
        return  $content['tab_bar'];
    }

}
